package com.example.w.service.impl;

import com.example.w.dto.PunchRecord;
import com.example.w.service.WeLinkIntegrationService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class WeLinkIntegrationServiceImpl implements WeLinkIntegrationService {
    @Value("${we.link.api.url}")
    private String apiURL;

    @Value("${we.link.api.key}")
    private String apiKey;

    @Value("${we.link.api.secret}")
    private String apiSecret;
    private static final long EXPIRATION_TIME = 60 * 60 * 1000; // 有效期为1小时

    public void sendToWeLink(PunchRecord record) throws IOException, InterruptedException {
        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("employeeId", record.getUserAccount());
        requestBody.put("punchTime", record.getPunchCardTime().toString());
        requestBody.put("punchType", record.getType());

        // 构建HTTP请求
        HttpClient httpClient = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(apiURL))
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + generateAccessToken(record.getUserAccount()))
                .POST(HttpRequest.BodyPublishers.ofString(new ObjectMapper().writeValueAsString(requestBody)))
                .build();

        // 发送请求
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

        // 检查响应
        if (response.statusCode() != 200) {
            throw new IOException("传输打卡数据给WeLink失败: " + response.body());
        }
    }

    //令牌设置
    private static String generateAccessToken(String employeeId) {
        // 生成随机的UUID作为令牌的一部分
        String tokenId = UUID.randomUUID().toString();

        // 当前时间
        Date now = new Date();
        // 设置过期时间为当前时间加上有效时长
        Date expirationTime = new Date(now.getTime() + EXPIRATION_TIME);

        // 构造令牌字符串，这里简单地拼接了一些信息，实际应用中应该使用加密算法和标准格式
        String token = tokenId + ":" + employeeId + ":" + expirationTime.getTime();
        return token;
    }

    public static void main(String[] args) {
        // 假设用户ID为"123"
        String accessToken = generateAccessToken("123");
        System.out.println("Generated Access Token: " + accessToken);
    }

}
